package com.cash.loan.common.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yangbo
 * @Date 2019-02-14 14:10
 */
@Component
public class RedisWithReentrantLock {

    @Autowired
    private RedisUtil redisUtil;

    private ThreadLocal<Map<String,Integer>> lockers = new ThreadLocal<>();

    /**
     * redis设置锁
     * @param key
     * @return
     */
    private boolean redisLock(String key) {
        return redisUtil.set(key,"","NX","EX",5L);
    }

    /**
     * 移除锁
     * @param key
     */
    private void redisUnlock(String key) {
        redisUtil.delete(key);
    }

    /**
     * 得到当前锁
     * @return
     */
    public Map<String,Integer> currentLockers() {
        Map<String,Integer> currentLockers = lockers.get();
        if(currentLockers != null && currentLockers.size() != 0) {
            return currentLockers;
        }
        lockers.set(new HashMap<>(2));
        return lockers.get();
    }

    /**
     * 设置可重入锁
     * @param key
     * @return
     */
    public boolean lock(String key) {
        Map<String,Integer> refs = this.currentLockers();
        Integer refCnt = refs.get(key);
        if(null != refCnt) {
            refs.put(key,refCnt + 1);
            return true;
        }
        boolean ok = this.redisLock(key);
        if(!ok) {
            return false;
        }
        refs.put(key,1);
        return true;
    }

    /**
     * 释放锁
     * @param key
     * @return
     */
    public boolean unlock(String key) {
        Map<String,Integer> refs = this.currentLockers();
        Integer refCnt = refs.get(key);
        if(refCnt == null) {
            return false;
        }
        refCnt -= 1;
        if(refCnt > 0) {
            refs.put(key,refCnt);
        } else {
            refs.remove(key);
            this.redisUnlock(key);
        }
        return true;
    }
}
